package cn.st4rlight.util.excel.strategy;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.OptionalInt;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;

import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import com.google.common.collect.Maps;

/**
 * 修改自官方的 {@link com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy}
 * @author st4rlight <st4rlight@163.com>
 * Created on 2024-04-15
 */
public class AutoWidthStrategy extends AbstractColumnWidthStyleStrategy {

    private static final int MAX_COLUMN_WIDTH = 255;
    private final Map<Integer, Map<Integer, Integer>> cache = MapUtils.newHashMapWithExpectedSize(8);


    @Override
    protected void setColumnWidth(
        WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell,
            Head head, Integer relativeRowIndex, Boolean isHead
    ) {
        boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
        if (!needSetWidth) {
            return;
        }

        Map<Integer, Integer> maxColumnWidthMap = cache.get(writeSheetHolder.getSheetNo());
        if (Objects.isNull(maxColumnWidthMap)) {
            maxColumnWidthMap = Maps.newHashMap();
            cache.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);
        }

        Integer columnWidth = this.getDataLength(cellDataList, cell, isHead);
        if (columnWidth < 0) {
            return;
        }
        columnWidth = Math.min(columnWidth, MAX_COLUMN_WIDTH);

        Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
        if (Objects.isNull(maxColumnWidth) || columnWidth > maxColumnWidth) {
            maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
            writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
        }
    }

    private Integer getDataLength(List<WriteCellData<?>> cellDataList, Cell cell, Boolean isHead) {
        if (BooleanUtils.isTrue(isHead)) {
            return cell.getStringCellValue().getBytes().length;
        }

        WriteCellData<?> cellData = cellDataList.get(0);
        CellDataTypeEnum type = cellData.getType();
        if (Objects.isNull(type)) {
            return -1;
        }

        switch (type) {
            case STRING:
                String value = cellData.getStringValue();
                OptionalInt optionalInt = Arrays.stream(value.split("\n"))
                        .mapToInt(item -> item.getBytes().length)
                        .max();
                return optionalInt.orElse(-1);
            case BOOLEAN:
                return cellData.getBooleanValue().toString().getBytes().length;
            case NUMBER:
                return cellData.getNumberValue().toString().getBytes().length;
            default:
                return -1;
        }
    }
}
